package core.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanConvert {
	public static final String[] excludeMethods = new String[] { "hashCode", "getClass", "wait", "equals",
			"notify", "notifyAll", "toString" };

	public static Map<String, String> convertToMap(Object targetObj, String[] excludeNamesIn)
			throws Exception {
		if (targetObj == null) {
			return null;
		}

		Map<String, String> result = new HashMap<String, String>();
		Method methods[] = targetObj.getClass().getMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			String properity;
			String value = null;

			if (methodName.indexOf("set") == 0) {
				continue;
			}

			boolean isExclude = false;
			for (String exclude : excludeMethods) {
				if (exclude.equals(methodName)) {
					isExclude = true;
					break;
				}
			}

			if (excludeNamesIn != null) {
				for (String exclude : excludeNamesIn) {
					if (exclude.equals(methodName)) {
						isExclude = true;
						break;
					}
				}
			}

			if (isExclude == true) {
				continue;
			}

			Object valueObj = method.invoke(targetObj, null);
			if(valueObj != null){
				value = String.valueOf(valueObj);
				properity = methodName.substring(3);
				properity = properity.substring(0, 1).toLowerCase() + properity.substring(1);
				result.put(properity, value);
			}
		}

		return result;
	}

	public static void printBeanValues(Object obj) {
		Class<?> clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				System.out.println(field.getName() + "=" + field.get(obj));
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void printBeanValues2(Object obj){
		Class<?> clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		System.out.println();
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				System.out.print(field.getName() + "=" + field.get(obj) + ", ");
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		System.out.println();
	}
}
